package com.lkl.demo.controller;

import com.lkl.demo.annotation.LoginUser;
import com.lkl.demo.entity.User;
import com.lkl.demo.service.IGoodsService;
import com.lkl.demo.vo.GoodsVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.List;

/**
 * 商品表
 *
 * @author likelong
 * @date 2022-07-26
 */
@Controller
@RequestMapping("/goods")
@Api(value = "商品表", tags = "商品表")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;

    @GetMapping("/toList")
    public String toList(Model model, @LoginUser User user) {

        if (user == null) {
            return "login";
        }

        List<GoodsVo> goodsVo = goodsService.findGoodsVo();
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsVo);
        return "goodsList";
    }

    /**
     * 跳转商品详情
     */
    @GetMapping("/toDetail/{goodsId}")
    public String toDetail(@LoginUser User user, @PathVariable Long goodsId,
                           Model model) {
        GoodsVo goodsDetail = goodsService.findGoodsVoByGoodsId(goodsId);

        model.addAttribute("user", user);
        model.addAttribute("goods", goodsDetail);

        Date startDate = goodsDetail.getStartDate();
        Date endDate = goodsDetail.getEndDate();
        Date nowDate = new Date();
        //秒杀状态 0 未开始 1 进行中 2 已结束
        int seckillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;

        if (nowDate.before(startDate)) {
            //秒杀还未开始 0
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
        } else if (nowDate.after(endDate)) {
            //秒杀已经结束
            seckillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            seckillStatus = 1;
        }

        model.addAttribute("seckillStatus", seckillStatus);
        model.addAttribute("remainSeconds", remainSeconds);
        return "goodsDetail";
    }
}
